﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Model;
using BLL;

public partial class MembershipCard_wechat_web_Order : WeiPage
{
    PRODUCTBO pbo = new PRODUCTBO();
    ShoppingCartBO sbo = new ShoppingCartBO();
    PersonInfoBO fbo = new PersonInfoBO();
    AddressBO abo = new AddressBO();
    REDP_DETAILBO rdbo = new REDP_DETAILBO();
    REDP_HEADBO rhbo = new REDP_HEADBO();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Request.QueryString["code"] != null)
            {
                try
                {
                    string url = string.Format(@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + GetAppid() + "&secret=d9bfd969e149c1844698cfd1f962bdad&code={0}&grant_type=authorization_code", Request.QueryString["code"].ToString());
                    string token = PostRequest(url);
                    if (token.Contains("7200"))
                    {
                        string[] b = token.Split('\"');
                        Session["FromUserName"] = b[13];
                        Session["ToUserName"] = "wx8ecea9aaa3d6162b";
                    }
                }
                catch (Exception)
                {

                }
            }
            if ((Request.QueryString["FromUserName"] != null || Session["FromUserName"] != null) && (Request.QueryString["ToUserName"] != null || Session["ToUserName"] != null))
            {
                string user = Request.QueryString["FromUserName"] == null ? Session["FromUserName"].ToString() : Request.QueryString["FromUserName"].ToString();
                string user2 = Request.QueryString["ToUserName"] == null ? Session["ToUserName"].ToString() : Request.QueryString["ToUserName"].ToString();
                Session["FromUserName"] = user;
                Session["ToUserName"] = user2;
                PersonInfo per = fbo.GetModel(user);
                if (per != null)
                {
                    List<ShoppingCart> list = sbo.GetModelList(" pid=" + per.ID );
                    if (list.Count > 0)
                    {
                        sumcar.InnerHtml = "<span><a href='ShopCar.aspx'><em class='indexicon4'></em><i>"+list.Count+"</i></a></span>";
                    }

                    List<Addresss> listadd = abo.GetModelList(" pid=" + per.ID + "  ORDER BY LAST_DATE DESC");
                    if (listadd.Count == 0)
                    {
                        dz.InnerHtml = "<p id='xxdz'>请添加你的收货地址</p>";
                    }
                    else
                    {
                        Addresss a = listadd[0];
                        dz.InnerHtml = string.Format(@"<p  id='xxdz'>收件人：{0}   {1}</p>
    <p>{2}</p>",a.Name,a.Phone,a.Address);
                    }
                }
                else
                {
                    // addcar.InnerHtml = "<font color='red'>请先注册和绑定</font>";
                    Response.Redirect("index2.aspx");
                }
            }

            if (Request.QueryString["id"] != null&&Request.QueryString["num"]!=null) //直接结算
            {
                Session["orderlx"] = "jx"; //购物车类型
                Session["orderid"] = Request.QueryString["id"].ToString();
                Session["ordernum"] = Request.QueryString["num"].ToString();
                PRODUCT p = pbo.GetModel(int.Parse(Request.QueryString["id"].ToString()));
                PRODUCT p1 = pbo.GetModel(456); //运费
                if (p != null&&p1!=null)
                {
                    xq.InnerHtml=string.Format(@" <strong>商品详情</strong>
    <p><a href='#'><img src='{0}' /></a><span>{1}</span>
    <span>数量：<bdo>{2}</bdo>   积分：<bdo>{3}分</bdo></span>
    </p>
 <p><a href='#'><img src='{5}' /></a><span>{6}</span>
    <span>数量：<bdo>1</bdo>   积分：<bdo>300分</bdo></span>
    </p>
    <div align='right' class='zongji'>共计：<bdo>{4}分</bdo></div>", (p.PicUrl == "" ? "images/m.png" : p.PicUrl), p.Name, Request.QueryString["num"].ToString(), p.Integral * int.Parse(Request.QueryString["num"].ToString()), int.Parse(Request.QueryString["num"].ToString()) * p.Integral + 300, (p1.PicUrl == "" ? "images/m.png" : p1.PicUrl), p1.Name);
                }
            }
            if (Request.QueryString["ids"] != null)  //购物车结算
            {
                Session["orderlx"] = "gwc"; //购物车类型
                Session["ids"] = Request.QueryString["ids"].ToString();
                xq.InnerHtml = " <strong>商品详情</strong>";
                int sum = 0;
                string[] ids = Request.QueryString["ids"].ToString().Substring(0,Request.QueryString["ids"].ToString().Length-1).Split(',');
                PRODUCT p1 = pbo.GetModel(456); //运费
                foreach (string id in ids)
                {
                    ShoppingCart c = sbo.GetModel(int.Parse(id));
                    if (c != null)
                    {
                        PRODUCT p = pbo.GetModel(int.Parse(c.RID.ToString()));
                        if (p != null)
                        {
                            xq.InnerHtml += string.Format(@"
    <p><a href='#'><img src='{0}' /></a><span>{1}</span>
    <span>数量：<bdo>{2}</bdo>   积分：<bdo>{3}分</bdo></span>
    </p>
    ", (p.PicUrl == "" ? "images/m.png" : p.PicUrl), p.Name, c.RNum, p.Integral * c.RNum);
                            sum += int.Parse(c.RNum.ToString()) * int.Parse(p.Integral.ToString());
                            
                        }
                    }
                }
                if (p1 != null)
                {
                    xq.InnerHtml += string.Format(@"
    <p><a href='#'><img src='{0}' /></a><span>{1}</span>
    <span>数量：<bdo>{2}</bdo>   积分：<bdo>{3}分</bdo></span>
    </p>
    ", (p1.PicUrl == "" ? "images/m.png" : p1.PicUrl), p1.Name, 1, p1.Integral);
                }
                sum += 300;
                lblZong.Text = sum.ToString();
                xq.InnerHtml += "<div align='right' class='zongji'>共计：<bdo>"+sum+"分</bdo></div>";
            }
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        if ((Request.QueryString["FromUserName"] != null || Session["FromUserName"] != null) && (Request.QueryString["ToUserName"] != null || Session["ToUserName"] != null))
        {
            string user = Request.QueryString["FromUserName"] == null ? Session["FromUserName"].ToString() : Request.QueryString["FromUserName"].ToString();
            string user2 = Request.QueryString["ToUserName"] == null ? Session["ToUserName"].ToString() : Request.QueryString["ToUserName"].ToString();
            Session["FromUserName"] = user;
            Session["ToUserName"] = user2;
            PersonInfo per = fbo.GetModel(user);
            if (per != null)
            {
                try
                {
                    PRODUCT p = pbo.GetModel(456); //运费
                    if(p!=null){
                    if (Session["orderlx"] != null)
                    {
                        List<Addresss> listadd = abo.GetModelList(" pid=" + per.ID + "  ORDER BY LAST_DATE DESC");
                        Addresss a = listadd[0];
                        if (Session["orderlx"].ToString() == "jx")
                        {
                            if (Session["orderid"] != null && Session["ordernum"] != null)
                            {
                                PRODUCT p1 = pbo.GetModel(int.Parse(Session["orderid"].ToString()));
                                REDP_HEAD he = new REDP_HEAD();
                                he.AddressID = a.ID;
                                he.MEMBERNO = per.PersonNo;
                                he.PayType = "积分";
                                he.POINTS = p1.Integral * int.Parse(Session["ordernum"].ToString()) + 300;
                                he.STATUS = "订单已申请";
                                he.STORE = 1;
                                he.TRANSDATE = DateTime.Now;
                                if (he.POINTS > per.SurplusIntegral)
                                {
                                    AlertMessage("积分不足，无法兑换");
                                    return;
                                }
                                string bh ="WX"+ DateTime.Now.ToString("yyyyMMddHHmmss") + new Random().Next(1000, 9999);

                                si_UploadExchageDetail_obService u = new si_UploadExchageDetail_obService();
                                dt_UploadExchangeDetail_req reu = new dt_UploadExchangeDetail_req();
                                reu.WV_CANCEL = "";
                                reu.ZCRMT017 = new ZCRMT017[] { new ZCRMT017() { WB_ORDER_ID = bh, MEMB_ID = per.PersonNo, POINT_CODE = "ZSMJF01", PROCESS_TYPE = "ZPDH",DIS_CHANNEL="22" } };
                                reu.ZCRMT018 = new ZCRMT018[] { new ZCRMT018() { OBJECT_ID = bh, PROCESS_TYPE = "ZPDH", NUMBER_INT = "1", PARTNER_NO = per.PersonNo, POSTING_DATE = DateTime.Now, POSTING_DATESpecified = true, PO_DATE_SOLD = DateTime.Now, PO_DATE_SOLDSpecified = true, ORDERED_PROD = "SM0003", QUANTITY = 1, QUANTITYSpecified = true, SALES_ORG_RESP_S = "C016", SALES_ORG_SHORT = "C016", DIVISION = "00", DIS_CHANNEL = "22" }, new ZCRMT018() { OBJECT_ID = bh, PROCESS_TYPE = "ZPDH", NUMBER_INT = "2", PARTNER_NO = per.PersonNo, POSTING_DATE = DateTime.Now, POSTING_DATESpecified = true, PO_DATE_SOLD = DateTime.Now, PO_DATE_SOLDSpecified = true, ORDERED_PROD = p1.SKU.Trim(), QUANTITY = int.Parse(Session["ordernum"].ToString()), QUANTITYSpecified = true, SALES_ORG_RESP_S = "C016", SALES_ORG_SHORT = "C016", DIVISION = "00", DIS_CHANNEL = "22" } };
                                dt_UploadExchangeDetail_res dtu = u.si_UploadExchageDetail_ob(reu);


                                if (dtu != null)
                                {
                                    if (dtu.WV_RETURN == "N")
                                    {
                                        AlertMessage(dtu.WV_MESSAGE);
                                        return;
                                    }
                                    else
                                    {
                                        int id = rhbo.Add(he);
                                        if (id > 0)
                                        {
                                            per.SurplusIntegral -= he.POINTS;
                                            fbo.Update(per);  //修改剩余积分

                                            REDP_DETAIL rd = new REDP_DETAIL();
                                            rd.NAME = p.Name;
                                            rd.PID = id;
                                            rd.POINTS = p.Integral;
                                            rd.SKU = p.SKU;
                                            rd.UNITS = 1;
                                            rdbo.Add(rd);

                                            rd.NAME = p1.Name;
                                            rd.PID = id;
                                            rd.POINTS = p1.Integral;
                                            rd.SKU = p1.SKU;
                                            rd.UNITS = int.Parse(Session["ordernum"].ToString());
                                            rdbo.Add(rd);

                                            p1.REDP_INV -= rd.UNITS;
                                            pbo.Update(p1); //修改商品剩余兑换数量

                                        }
                                    }

                                }


                            }
                        }
                        else if (Session["orderlx"].ToString() == "gwc")
                        {
                            if (Session["ids"] != null)
                            {
                                si_UploadExchageDetail_obService u = new si_UploadExchageDetail_obService();
                                dt_UploadExchangeDetail_req reu = new dt_UploadExchangeDetail_req();
                                reu.WV_CANCEL = "";
                                string[] ids = Request.QueryString["ids"].ToString().Substring(0, Request.QueryString["ids"].ToString().Length - 1).Split(',');
                                REDP_HEAD he = new REDP_HEAD();
                                he.AddressID = a.ID;
                                he.MEMBERNO = per.PersonNo;
                                he.PayType = "积分";
                                he.POINTS = int.Parse(lblZong.Text) + 300;
                                he.STATUS = "订单已申请";
                                he.STORE = 1;
                                he.TRANSDATE = DateTime.Now;
                                if (he.POINTS > per.SurplusIntegral)
                                {
                                    AlertMessage("积分不足，无法兑换");
                                    return;
                                }
                                //int hid = rhbo.Add(he);
                                //if (hid > 0)
                                //{
                                    //per.SurplusIntegral -= he.POINTS;
                                    //fbo.Update(per);  //修改剩余积分
                                string bh = "WX" + DateTime.Now.ToString("yyyyMMddHHmmss") + new Random().Next(1000, 9999);
                                    reu.ZCRMT017 = new ZCRMT017[] { new ZCRMT017() { WB_ORDER_ID = bh, MEMB_ID = per.PersonNo, POINT_CODE = "ZSMJF01", PROCESS_TYPE = "ZPDH",DIS_CHANNEL="22" } };
                                    reu.ZCRMT018 = new ZCRMT018[ids.Length + 1];
                                    int row = 0;
                                    foreach (string id in ids)
                                    {
                                        ShoppingCart c = sbo.GetModel(int.Parse(id));
                                        if (c != null)
                                        {
                                            PRODUCT p1 = pbo.GetModel(int.Parse(c.RID.ToString()));
                                            if (p1 != null)
                                            {
                                                //REDP_DETAIL rd = new REDP_DETAIL();
                                                //rd.NAME = p1.Name;
                                                //rd.PID = hid;
                                                //rd.POINTS = p1.Integral;
                                                //rd.SKU = p1.SKU;
                                                //rd.UNITS = c.RNum;
                                                //rdbo.Add(rd);
                                                reu.ZCRMT018[row] = new ZCRMT018() { OBJECT_ID = bh, PROCESS_TYPE = "ZPDH", NUMBER_INT = (row+1).ToString(), PARTNER_NO = per.PersonNo, POSTING_DATE = DateTime.Now,POSTING_DATESpecified=true, PO_DATE_SOLD = DateTime.Now,PO_DATE_SOLDSpecified=true, ORDERED_PROD = p1.SKU.Trim(), QUANTITY = int.Parse(c.RNum.ToString()),QUANTITYSpecified=true,DIS_CHANNEL="22", SALES_ORG_RESP_S = "C016", SALES_ORG_SHORT = "C016", DIVISION = "00" };
                                                row++;
                                                //sbo.Delete(c.ID);

                                                //p1.REDP_INV -= rd.UNITS;
                                                //pbo.Update(p1); //修改商品剩余兑换数量
                                            }

                                        }
                                    }
                                    //REDP_DETAIL r = new REDP_DETAIL();
                                    //r.NAME = p.Name;
                                    //r.PID = hid;
                                    //r.POINTS = p.Integral;
                                    //r.SKU = p.SKU;
                                    //r.UNITS = 1;
                                    //rdbo.Add(r);
                                    reu.ZCRMT018[row] = new ZCRMT018() { OBJECT_ID = bh, PROCESS_TYPE = "ZPDH", NUMBER_INT = (row + 1).ToString(), PARTNER_NO = per.PersonNo, POSTING_DATE = DateTime.Now, PO_DATE_SOLDSpecified = true, POSTING_DATESpecified = true, DIS_CHANNEL = "22", QUANTITYSpecified = true, PO_DATE_SOLD = DateTime.Now, ORDERED_PROD = "SM0003", QUANTITY = 1, SALES_ORG_RESP_S = "C016", SALES_ORG_SHORT = "C016", DIVISION = "00" };
                                //}


                                dt_UploadExchangeDetail_res dtu = u.si_UploadExchageDetail_ob(reu);
                                if(dtu!=null)
                                {
                                    if (dtu.WV_RETURN == "N")
                                    {
                                       // AlertMessage(per.PersonNo);
                                        AlertMessage(dtu.WV_MESSAGE);
                                        return;
                                    }
                                    else
                                    {
                                         ids = Request.QueryString["ids"].ToString().Substring(0, Request.QueryString["ids"].ToString().Length - 1).Split(',');
                                        int hid = rhbo.Add(he);
                                        if (hid > 0)
                                        {
                                            per.SurplusIntegral -= he.POINTS;
                                            fbo.Update(per);  //修改剩余积分
                                           // string bh = DateTime.Now.ToString("yyyyMMddHHmmss");
                                            //reu.ZCRMT017 = new ZCRMT017[] { new ZCRMT017() { WB_ORDER_ID = bh, MEMB_ID = per.PersonNo, POINT_CODE = "ZSMJF01", PROCESS_TYPE = "ZPDH" } };
                                            //reu.ZCRMT018 = new ZCRMT018[ids.Length + 1];
                                            //int row = 0;
                                            foreach (string id in ids)
                                            {
                                                ShoppingCart c = sbo.GetModel(int.Parse(id));
                                                if (c != null)
                                                {
                                                    PRODUCT p1 = pbo.GetModel(int.Parse(c.RID.ToString()));
                                                    if (p1 != null)
                                                    {
                                                        REDP_DETAIL rd = new REDP_DETAIL();
                                                        rd.NAME = p1.Name;
                                                        rd.PID = hid;
                                                        rd.POINTS = p1.Integral;
                                                        rd.SKU = p1.SKU;
                                                        rd.UNITS = c.RNum;
                                                        rdbo.Add(rd);
                                                        //reu.ZCRMT018[row] = new ZCRMT018() { OBJECT_ID = bh, PROCESS_TYPE = "ZPDH", NUMBER_INT = "1", PARTNER_NO = per.PersonNo, POSTING_DATE = DateTime.Now, PO_DATE_SOLD = DateTime.Now, ORDERED_PROD = p1.SKU, QUANTITY = 1, SALES_ORG_RESP_S = "C020", SALES_ORG_SHORT = "C020", DIVISION = "00" };
                                                        //row++;
                                                        sbo.Delete(c.ID);

                                                        p1.REDP_INV -= rd.UNITS;
                                                        pbo.Update(p1); //修改商品剩余兑换数量
                                                    }

                                                }
                                            }
                                            REDP_DETAIL r = new REDP_DETAIL();
                                            r.NAME = p.Name;
                                            r.PID = hid;
                                            r.POINTS = p.Integral;
                                            r.SKU = p.SKU;
                                            r.UNITS = 1;
                                            rdbo.Add(r);
                                            //reu.ZCRMT018[row] = new ZCRMT018() { OBJECT_ID = bh, PROCESS_TYPE = "ZPDH", NUMBER_INT = "1", PARTNER_NO = per.PersonNo, POSTING_DATE = DateTime.Now, PO_DATE_SOLD = DateTime.Now, ORDERED_PROD = p.SKU, QUANTITY = 1, SALES_ORG_RESP_S = "C020", SALES_ORG_SHORT = "C020", DIVISION = "00" };
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                }
                catch (Exception)
                {


                }
                List<ShoppingCart> list = sbo.GetModelList(" pid=" + per.ID);
                if (list.Count > 0)
                {
                    sumcar.InnerHtml = "<span><a href='ShopCar.aspx'><em class='indexicon4'></em><i>" + list.Count + "</i></a></span>";
                }
                else
                {
                    sumcar.InnerHtml = "<span><a href='ShopCar.aspx'><em class='indexicon4'></em></a></span>";
                }
                AlertMessage("订单申请已提交");
                tj.Visible = false;
            }
        }

    }

    
}